/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.UserquestionlogQueryCriteria;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.utils.PageResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.IntStream;

/**
* @author shitou
* @date 2024-05-29
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "试题答题记录管理")
@RequestMapping("/api/userquestionlog")
@Validated
public class UserquestionlogController {

    private final UserquestionlogService userquestionlogService;

    private final UserexercisesetlogService userexercisesetlogService;

    private final QuestionoptionService questionoptionService;

    private final ExercisesetandquestionService exercisesetandquestionService;

    private final UserMapper userMapper;

    private final QuestionService questionService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('userquestionlog:list')")
    public void exportUserquestionlog(HttpServletResponse response, UserquestionlogQueryCriteria criteria) throws IOException {
        userquestionlogService.download(userquestionlogService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询试题答题记录")
    @ApiOperation("查询试题答题记录")
//    @PreAuthorize("@el.check('userquestionlog:list')")
    public ResponseEntity<PageResult<Userquestionlog>> queryUserquestionlog(UserquestionlogQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(userquestionlogService.queryAll(criteria,page),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增试题答题记录")
    @ApiOperation("新增试题答题记录")
//    @PreAuthorize("@el.check('userquestionlog:add')")
    public ResponseEntity<Object> createUserquestionlog(@RequestBody Userquestionlog resources){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teachId",resources.getTeachid());

        if(resources.getTeachchapterid()!=null){
            queryWrapper.eq("teachChapterId",resources.getTeachchapterid());
        }
        if(resources.getTeachsubsectionid()!=null){

            queryWrapper.eq("teachSubsectionId",resources.getTeachsubsectionid());
        }
        if(resources.getSubsectionpluginsid()!=null){

            queryWrapper.eq("subsectionExerciseSetId",resources.getSubsectionExerciseSetId());
        }
        if(resources.getCourseid()!=null){

            queryWrapper.eq("courseId",resources.getCourseid());
        }
        if(resources.getExercisesetid()!=null){

            queryWrapper.eq("exerciseSetId",resources.getExercisesetid());

        }
        if(resources.getType()!=null){

            queryWrapper.eq("type",resources.getType());
        }

        Userexercisesetlog userexercisesetlog = userexercisesetlogService.getOneMsg(queryWrapper);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 生成时间戳
        String timestamp = sdf.format(new Date());
        System.out.println("==userexercisesetlog=="+userexercisesetlog);
        if(userexercisesetlog!=null && userexercisesetlog.getId()!=null){
            if(userexercisesetlog.getIscomplete().equals("1")){
                return new ResponseEntity<>("该试卷已提交",HttpStatus.OK);
            }
            resources.setUserexercisesetlogid(userexercisesetlog.getId());
        } else {
            Userexercisesetlog userexercisesetlog1 = new Userexercisesetlog();
            if(resources.getCourseid()!=null){

                userexercisesetlog1.setCourseid(resources.getCourseid());
            }
            if(resources.getTeachid()!=null){
                userexercisesetlog1.setTeachid(resources.getTeachid());
            }

            userexercisesetlog1.setType(resources.getType());
            userexercisesetlog1.setTeachchapterid(resources.getTeachchapterid());
            userexercisesetlog1.setTeachsubsectionid(resources.getTeachsubsectionid());
            userexercisesetlog1.setSubsectionexercisesetid(resources.getSubsectionExerciseSetId());
            userexercisesetlog1.setExercisesetid(resources.getExercisesetid());
            userexercisesetlog1.setUserid(resources.getUserid());
            userexercisesetlog1.setType(resources.getType());


            userexercisesetlog1.setCreatetime(timestamp);

            userexercisesetlogService.create(userexercisesetlog1);

            resources.setUserexercisesetlogid(userexercisesetlog1.getId());
        }
        resources.setCreatetime(timestamp);

        //判断是否正确
        QueryWrapper optionQueryWrapper = new QueryWrapper<>();
        optionQueryWrapper.ge("questionid",resources.getQuestionid());
        List<Questionoption> questionoptionList =  questionoptionService.list(optionQueryWrapper);

        if(resources.getQuestiontype() !=null && resources.getQuestiontype() == 0){//单选 && 判断
            resources.setIstrue(0);
            for(Questionoption questionoption:questionoptionList){
                if(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(resources.getContent()))){
                    resources.setIstrue(1);
                }
            }

        } else if(resources.getQuestiontype() !=null && resources.getQuestiontype() == 1){//多选

            List<Integer> contents = new ArrayList<>();
            if(!resources.getContent().isEmpty()){
                contents = JSON.parseObject(resources.getContent(), (Type) List.class);
            }
            List<Integer> result = new ArrayList<>();
            List<String> result2 = new ArrayList<>();
            for(Questionoption questionoption:questionoptionList){
                for(Integer content: contents){
                    if(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(content)) && questionoption.getIsTrue() == 1){
                        result.add(content);
                    }
                }
                if(questionoption!=null && questionoption.getIsTrue() !=null && questionoption.getIsTrue() == 1){
                    result2.add(String.valueOf(questionoption.getId()));
                }
            }
            if(result2.size() == result.size()){
                resources.setIstrue(1);
            } else {
                resources.setIstrue(0);
            }
        }else if(resources.getQuestiontype() !=null && resources.getQuestiontype() == 2){//判断
            resources.setIstrue(0);
            for(Questionoption questionoption:questionoptionList){
                System.out.println(String.valueOf(questionoption.getId()));
                System.out.println(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(resources.getContent())));
                System.out.println("resources.getContent()"+resources.getContent());
                System.out.println("questionoption.getIsTrue()"+questionoption.getIsTrue());
                if(Objects.equals(String.valueOf(questionoption.getId()), String.valueOf(resources.getContent())) && questionoption.getIsTrue() == 1){
                    resources.setIstrue(1);
                }
            }
        } else if(resources.getQuestiontype() !=null && resources.getQuestiontype() == 3){//填空


            if(!resources.getContent().isEmpty()){
                List<String> contents = null;
                contents = JSON.parseObject(resources.getContent(), (Type) List.class);

                QueryWrapper queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("id",resources.getQuestionid());
                Question question = questionService.getOne(queryWrapper2);
                if(question.getIsTurnFill()!=null && question.getIsTurnFill() == 1){
                    resources.setIstrue(0);
                    List<String> finalContents = contents;
                    IntStream.range(0,contents.size()).forEach(item1 -> {
                        IntStream.range(0,questionoptionList.size()).forEach(item2 -> {
                            if(item1 == item2){
                                if(finalContents.get(item1) == questionoptionList.get(item2).getName()){
                                    resources.setIstrue(1);
                                }
                            }
                        });

                    });

                } else {

                    resources.setIstrue(0);
                    for(Questionoption questionoption:questionoptionList){
                        for(String content: contents){
                            if(Objects.equals(String.valueOf(questionoption.getName()), content)){
                                resources.setIstrue(1);
                            }
                        }
                    }

                }
            }


        }
//        else if(resources.getQuestiontype() !=null && resources.getQuestiontype() == 4){//简单
//            resources.setPath();
//        }

        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("exerciseSetId",resources.getExercisesetid());
        queryWrapper2.eq("questionId",resources.getQuestionid());
        Exercisesetandquestion exercisesetandquestion = exercisesetandquestionService.getOne(queryWrapper2);

        if(resources.getIstrue()!=null && resources.getIstrue() == 1){
            resources.setScore(exercisesetandquestion.getScore());
        } else {
            resources.setScore("0");
        }
        System.out.println("resources.setScore()"+resources.getScore());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
//        System.out.println("userexercisesetlog1"+resources);
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teachId",resources.getTeachid());
        queryWrapper1.eq("teachChapterId", resources.getTeachchapterid());
        queryWrapper1.eq("teachSubsectionId", resources.getTeachsubsectionid());
        queryWrapper1.eq("subsectionPluginsId", resources.getSubsectionpluginsid());
        queryWrapper1.eq("subsectionExerciseSetId", resources.getSubsectionExerciseSetId());
        queryWrapper1.eq("exerciseSetId", resources.getExercisesetid());
        queryWrapper1.eq("type", resources.getType());
        queryWrapper1.eq("courseId", resources.getCourseid());
        queryWrapper1.eq("questionId", resources.getQuestionid());
        queryWrapper1.eq("questionType", resources.getQuestiontype());
        queryWrapper1.eq("userId", currentUser.getId());
        Userquestionlog userquestionlog = userquestionlogService.getOne(queryWrapper1);

        if(userquestionlog!=null){
            resources.setId(userquestionlog.getId());
            userquestionlogService.update(resources);

        } else {
            userquestionlogService.create(resources);

        }

        return new ResponseEntity<>(HttpStatus.OK);
    }

    @PutMapping
    @Log("修改试题答题记录")
    @ApiOperation("修改试题答题记录")
//    @PreAuthorize("@el.check('userquestionlog:edit')")
    public ResponseEntity<Object> updateUserquestionlog(@Validated @RequestBody Userquestionlog resources){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teachId",resources.getTeachid());
        queryWrapper.eq("teachChapterId",resources.getTeachid());
        queryWrapper.eq("teachSubsectionId",resources.getTeachid());
        queryWrapper.eq("subsectionExerciseSetId",resources.getTeachid());
        queryWrapper.eq("courseId",resources.getTeachid());
        queryWrapper.eq("exerciseSetId",resources.getTeachid());
        queryWrapper.eq("userId",resources.getTeachid());
        queryWrapper.eq("type",resources.getType());
        Userexercisesetlog userexercisesetlog = userexercisesetlogService.getOne(queryWrapper);

        if(userexercisesetlog!=null){
            resources.setUserexercisesetlogid(userexercisesetlog.getId());
        }



        //判断是否正确
        QueryWrapper optionQueryWrapper = new QueryWrapper<>();
        optionQueryWrapper.ge("questionid",resources.getQuestionid());
        List<Questionoption> questionoptionList =  questionoptionService.list(optionQueryWrapper);

        if(resources.getQuestiontype() == 0){//单选 && 判断
            for(Questionoption questionoption:questionoptionList){
                if(Objects.equals(String.valueOf(questionoption.getId()), resources.getContent())){
                    resources.setIstrue(1);
                } else {
                    resources.setIstrue(0);
                }
            }

        } else if(resources.getQuestiontype() == 1){//多选

            List<Integer> contents = JSON.parseObject(resources.getContent(), (Type) List.class);

            List<Integer> result = new ArrayList<>();
            List<Integer> result2 = new ArrayList<>();
            for(Questionoption questionoption:questionoptionList){
                for(Integer content: contents){
                    if(Objects.equals(String.valueOf(questionoption.getId()), content) && questionoption.getIsTrue() == 1){
                        result.add(content);
                    }
                }
                if(questionoption.getIsTrue() == 1){
                    result2.add(questionoption.getId());
                }
            }
            if(result2.size() == result.size()){
                resources.setIstrue(1);
            } else {
                resources.setIstrue(0);
            }
        } else if(resources.getQuestiontype() == 2){
            for(Questionoption questionoption:questionoptionList){
                if(Objects.equals(String.valueOf(questionoption.getId()), resources.getContent())){
                    resources.setIstrue(1);
                } else {
                    resources.setIstrue(0);
                }
            }
        }

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teachId",resources.getTeachid());
        queryWrapper1.eq("teachChapterId",resources.getTeachchapterid());
        queryWrapper1.eq("teachSubsectionId",resources.getTeachsubsectionid());
        queryWrapper1.eq("subsectionPluginsId",resources.getSubsectionpluginsid());
        queryWrapper1.eq("exerciseSetId",resources.getExercisesetid());
        queryWrapper1.eq("questionId",resources.getQuestionid());
        queryWrapper1.eq("userId",currentUser.getId());
        queryWrapper1.eq("subsectionExerciseSetId",resources.getSubsectionExerciseSetId());
        queryWrapper1.eq("questionType",resources.getQuestiontype());
        queryWrapper1.eq("userExerciseSetLogId",resources.getUserexercisesetlogid());
        queryWrapper1.eq("type",resources.getType());
        queryWrapper1.eq("courseId",resources.getCourseid());




        Userquestionlog userquestionlog = userquestionlogService.getOne(queryWrapper1);

        resources.setId(userquestionlog.getId());

        userquestionlogService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除试题答题记录")
    @ApiOperation("删除试题答题记录")
//    @PreAuthorize("@el.check('userquestionlog:del')")
    public ResponseEntity<Object> deleteUserquestionlog(@RequestBody List<Integer> ids) {
        userquestionlogService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}